package com.thoughtworks.studio.tools.cardkit.parser;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExcelParser {
	private HSSFWorkbook workbook ;
	 
	 public ExcelParser(File excelFile) throws FileNotFoundException, IOException{

	  workbook = new HSSFWorkbook(new FileInputStream(excelFile));
	 }



	 public List<List<Object>> getDatasInSheet(int sheetNumber) throws FileNotFoundException, IOException{
		 List<List<Object>> result = new ArrayList<List<Object>>();
	  

	  HSSFSheet sheet = workbook.getSheetAt(sheetNumber);
	  

	  int rowCount = sheet.getLastRowNum();
	  if (rowCount < 1) {
	   return result;
	  }
	  

	  for (int rowIndex = 0; rowIndex <= rowCount; rowIndex++) {
	   

	   HSSFRow row = sheet.getRow(rowIndex);
	   
	   if (row != null) {
	    
	    List<Object> rowData = new ArrayList<Object>();
	    

	    int columnCount = row.getLastCellNum();
	    

	    for (short columnIndex = 0; columnIndex < columnCount; columnIndex++) {
	     HSSFCell cell = row.getCell(columnIndex);
	     

	     Object cellStr = this.getCellString(cell);
	     
	     rowData.add(cellStr);
	     
	    }
	    
	    result.add(rowData);
	   }
	  }
	  return result;
	 }
	 

	 protected Object getCellString(HSSFCell cell){
	  Object result = null;
	  if (cell != null) {

	   int cellType = cell.getCellType();
	   
	   switch(cellType){
	   
	   case HSSFCell.CELL_TYPE_STRING :
	    result = cell.getRichStringCellValue().getString();
	    break;
	   case HSSFCell.CELL_TYPE_NUMERIC:
	    result=cell.getNumericCellValue();
	    break;
	   case HSSFCell.CELL_TYPE_FORMULA:
	    result = cell.getNumericCellValue();
	    break;
	   case HSSFCell.CELL_TYPE_ERROR:
	    result=null;
	    break;
	   case HSSFCell.CELL_TYPE_BOOLEAN:
	    result=cell.getBooleanCellValue();
	    break;
	   case HSSFCell.CELL_TYPE_BLANK:
	    result=null;
	    break;
	   }
	  }
	  return result;
	 }
}
